package com.zp.self.module.level_4_算法练习.数据结构.String;

import org.junit.Test;

import java.util.*;

/**
 * @author By ZengPeng
 */
public class 力扣_720_词典中最长的单词 {
    @Test
    public void main() {

        System.out.println(longestWord(new String[]{"w","wo","wor","worl", "world"}));
        System.out.println(longestWord(new String[]{"a", "banana", "app", "appl", "ap", "apply", "apple"}));
        System.out.println(longestWord(new String[]{"yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y"}));
    }

    /**
    题目：给出一个字符串数组 words 组成的一本英语词典。
     返回 words 中最长的一个单词，该单词是由 words 词典中其他单词逐步添加一个字母组成。
     若其中有多个可行的答案，则返回答案中字典序最小的单词。若无答案，则返回空字符串。

    分析：【P 💜💜💜】
       1.排序+遍历：排序后字母按指定规律排序. -- 不行啊 我要找到我之前的字符串是否存在数组中，最好还是用hahs吧
       2.hash: 将相同长度字符放入同一个set中，依次向上遍历
                --执行用时：18 ms, 在所有 Java 提交中击败了24.04%的用户
       3.大神：用集合res记录可行的字符串，后续的字符判断是否符号时，用res判断是否包含

    边界值 & 注意点：
       1.["yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y"]  --e都不存在
     **/
    public String longestWord(String[] words) {
        Map<Integer, List<String>> map = new HashMap<>();
        for (String word : words) {
            if(!map.containsKey(word.length())){
               map.put(word.length(),new ArrayList<>());
            }
            List<String> stringSet = map.get(word.length());
            stringSet.add(word);
        }
        int len =1;
        String maxString="";
        map.put(0,new ArrayList<>());
        map.get(0).add(maxString);
        while (map.containsKey(len)){
            List<String> proSet = map.get(len-1);
            List<String> list = map.get(len);
            for (int i = 0; i < list.size(); i++) {
                String s = list.get(i);
                if(proSet.contains(s.substring(0,s.length()-1))){
                    if(maxString.length()<s.length()  || maxString.compareTo(s)>0){
                        maxString = s;
                    }
                }else{
                    list.remove(s);
                    i--;
                }
            }
            len++;
        }
        return maxString;
    }
}
